'use strict';
import React from "react";
import {
    Keyboard,
    StyleSheet,
    Text,
    TextInput,
    TextInputComponent,
    TouchableOpacity,
    TouchableOpacityComponent,
    View
} from "react-native";
import Container from "../../component/common/Container";
import ImageView from "../../component/common/ImageView";
import {KeyboardAwareScrollView} from "react-native-keyboard-aware-scroll-view";
import Button from "../../component/common/Button";
import {Stepper} from "teaset";
import NavigationBar from "../../component/navigation/NavigationBar";
import {inject, observer} from "mobx-react";

@inject('loginStore')
@observer
class PointExchange extends React.Component {

    constructor(props) {
        super(props);
        const {params} = this.props.navigation.state;
        // console.log('params-------->',params);
        this.item = params.item;
        this.state = {count: 1, selectArea: '', province: '', city: '', district: ''};
        this.inputItems = [
            {title: '收货人', placeholder: '请输入收货人姓名', isInput: true},
            {title: '联系电话', placeholder: '请输入联系电话', isInput: true},
            {title: '收货地址', placeholder: '请选择收货地址', isInput: false},
            {title: '详细地址', placeholder: '请输入详细地址', isInput: true},
        ];
        this.inputText = {};
    }

    _onStepChange = (value) => {
        // console.log('value----------->',value);
        this.setState({count: value})
    };

    _onChangeText = (title, text) => {
        // console.log(title,text);
        this.inputText[title] = text
    };

    _onPressSelectCity = () => {
        Keyboard.dismiss();
        ActionsManager.showArea((data) => {
            // console.log(data);
            // let s1 = data[0].name;
            // let s2 = data[1].name;
            // let s3 = data[2].name;
            let s1 = data[0];
            let s2 = data[1];
            let s3 = data[2];
            let position;
            if (s1 === s2) {
                position = `${s2}-${s3}`;
            } else {
                position = `${s1}-${s2}-${s3}`;
            }
            this.setState({selectArea: position, province: data[0].name, city: data[1].name, district: data[2].name});
            ActionsManager.hide();
        })
    };

    _onPressExchange = async () => {
        const {loginStore} = this.props;
        if (!this.inputText['收货人'] || !this.inputText['联系电话'] || !this.state.selectArea || !this.inputText['详细地址']) {
            ToastManager.show('必填项不能为空')
            return;
        }
        const data = {
            create_user: global.secretKey,
            goods_id: this.item.goods_id,
            order_count: this.state.count,
            order_amounts: this.item.goods_price * this.state.count,
            order_phone: this.inputText['联系电话'],
            order_consignee: this.inputText['收货人'],
            order_address: this.inputText['详细地址'],
            order_province: this.state.province,
            order_city: this.state.city,
            order_district: this.state.district,
        };
        ToastManager.showLoading(true);
        const result = await Services.post(ServicesApi.GOODS_EXCHANGE, data);
        ToastManager.showLoading(false);
        // console.log('积分兑换返回------------->',result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            ToastManager.show('兑换成功!');
            await loginStore.getUserData(global.secretKey)
            RouterHelper.goBack();
        } else {
            ToastManager.show(result.dec || 'error');
        }
    };

    renderHeader = () => {
        const width = SCREEN_WIDTH * 0.439;
        const height = width * 0.719;
        if (this.item.goods_picture) {
            this.item.goods_picture = this.item.goods_picture.replace(',', '');
        }
        const goods_imgs = this.item.goods_picture ? `${ServicesApi.QI_NIU_LINK}${this.item.goods_picture}` : '';
        return (
            <View style={styles.headerView}>
                <ImageView
                    resizeMode={'cover'}
                    style={[styles.goodsImg, {width, height}]}
                    source={goods_imgs ? {uri: goods_imgs} : Images.img_shop_default}
                />
                <View style={[styles.headerRightView, {height}]}>
                    <Text style={styles.headerTitle}>{this.item.goods_name}</Text>
                    <View style={styles.headerBottomView}>
                        <Text style={styles.headerPoint}>{`${this.item.goods_price}积分`}</Text>
                        <Stepper
                            defaultValue={1}
                            min={1}
                            onChange={this._onStepChange}
                        />
                    </View>
                </View>
            </View>
        )
    };

    renderInputContent = () => {
        if (this.inputItems.length < 1) {
            return null;
        }
        let content = this.inputItems.map((item, index) => {
            return (
                <View
                    key={index}
                    style={styles.inputView}
                >
                    <Text style={styles.inputTitle}>{item.title}</Text>
                    {item.isInput ?
                        <TextInput
                            style={styles.input}
                            placeholder={item.placeholder}
                            placeholderTextColor={'#adadad'}
                            keyboardType={item.title === '联系电话' ? "phone-pad" : "default"}
                            onChangeText={(text) => this._onChangeText(item.title, text)}
                        /> :
                        <TouchableOpacity style={styles.areaView} onPress={this._onPressSelectCity}>
                            <Text
                                style={[styles.areaText, {color: this.state.selectArea ? '#333' : '#adadad'}]}>{this.state.selectArea ? this.state.selectArea : item.placeholder}</Text>
                            <ImageView
                                style={{width: 6, height: 11, marginLeft: 3}}
                                source={Images.icon_up_down}
                            />
                        </TouchableOpacity>}
                </View>
            );
        });
        return content;
    };

    render() {
        const {params} = this.props.navigation.state;
        const pageTitle = params.pageTitle || '积分兑换';

        return (
            <Container>
                <NavigationBar
                    title={pageTitle}
                />

                <KeyboardAwareScrollView
                    style={styles.scroll}
                    keyboardShouldPersistTaps={'handled'}
                >
                    {this.renderHeader()}
                    <View style={styles.content}>
                        {this.renderInputContent()}
                    </View>
                </KeyboardAwareScrollView>
                <View style={styles.footerView}>
                    <Text
                        style={styles.bottomPoint}>{`积分：${parseFloat(this.item.goods_price * this.state.count).toFixed(0)}`}</Text>
                    <Button
                        style={styles.bottomButton}
                        titleStyle={styles.buttonTitle}
                        title={'立即兑换'}
                        onPress={this._onPressExchange}
                    />
                </View>
            </Container>
        );
    }
}

const styles = StyleSheet.create({
    scroll: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },
    headerView: {
        padding: 15,
        marginVertical: 10,
        flexDirection: 'row',
        backgroundColor: '#fff',
    },
    goodsImg: {
        borderRadius: 5,
        backgroundColor: '#fefefe',
    },
    headerRightView: {
        marginLeft: 10,
        flex: 1,
        paddingVertical: 3,
        justifyContent: 'space-between',
    },
    headerTitle: {
        fontSize: FontSize(14),
        color: "#585858",
    },
    headerBottomView: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    headerPoint: {
        fontSize: FontSize(16),
        color: "#ffa64f",
    },
    stepper: {},
    content: {
        backgroundColor: '#fff',
    },
    inputView: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 15,
        paddingHorizontal: 15,
        borderBottomColor: '#ececec',
        borderBottomWidth: Theme.minPixel,
    },
    inputTitle: {
        fontSize: FontSize(16),
        color: "#333",
    },
    input: {
        flex: 1,
        textAlign: 'right',
        fontSize: FontSize(14),
        color: '#333',
        padding: 0,
    },
    areaView: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1,
        justifyContent: 'flex-end',

    },
    areaText: {
        fontSize: FontSize(14),
    },
    //底部
    footerView: {
        paddingLeft: 15,
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#fff',
        borderColor: Theme.borderColor,
        borderTopWidth: Theme.minPixel,
        justifyContent: 'space-between',
    },
    bottomPoint: {
        color: "#333",
        fontSize: FontSize(16),
    },
    bottomButton: {
        borderRadius: 0,
        paddingVertical: 15,
        paddingHorizontal: 19,
        backgroundColor: "#ffa64f",
    },
    buttonTitle: {
        fontSize: FontSize(16),
        color: "#ffffff",
    },
});

export default PointExchange